package com.ss.ugc.android.alphavideoplayer.utils

import android.content.Context
import android.content.res.AssetManager
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


object AssetUtils {

    private const val TAG = "AssetUtils"

    const val ASSET_DIR_NAME = "assets"

    fun copyFileFromAssetsToInternalStorage(context: Context) {
        val assetManager: AssetManager = context.assets

        val dirName = "demoRes"
        val list = assetManager.list(dirName)
        list?.forEach { filename ->
            try {
                val assetFile = "${dirName}/$filename"
                val input = assetManager.open(assetFile) // 打开 Asset 中的文件流
                val outFile: File = File(context.getExternalFilesDir(ASSET_DIR_NAME), assetFile) // 内部存储文件路径
                if (outFile.exists()) {
                    outFile.delete()
                }
                outFile.parentFile?.mkdirs()

                val out: OutputStream = FileOutputStream(outFile)
                val buffer = ByteArray(1024)
                var read: Int

                // 将 Asset 文件写入内部存储
                while ((input.read(buffer).also { read = it }) != -1) {
                    out.write(buffer, 0, read)
                }

                input.close()
                out.close()

                // 文件已复制到内部存储
                Log.d(TAG, "File copied to internal storage: $assetFile")
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}